package com.jacobson.huobi.mvp

import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.MediaStore
import android.view.View
import android.widget.Toast
import androidx.core.content.FileProvider
import com.alibaba.fastjson.JSONObject
import com.bumptech.glide.Glide
import com.jacobson.core.base.Immersive
import com.jacobson.core.di.components.AppComponent
import com.jacobson.core.di.modules.ActivityModule
import com.jacobson.core.mvp.BaseMvpActivity
import com.jacobson.huobi.Constants
import com.jacobson.huobi.R
import com.jacobson.huobi.common.constants.CommonConstant
import com.jacobson.huobi.common.constants.KycAuthStatusConstant
import com.jacobson.huobi.di.components.DaggerKycAuthActivityComponent
import com.jacobson.huobi.di.modules.KycAuthActivityModule
import com.jacobson.huobi.entities.response.CommonResponse
import com.jacobson.huobi.entities.vo.KycAuthResVo
import com.jacobson.huobi.mvp.contract.KycAuthContract
import com.jacobson.huobi.utils.DataUtil
import com.jacobson.huobi.utils.PreferencesUtil
import com.jacobson.huobi.utils.ResourcesUtil
import kotlinx.android.synthetic.main.activity_kyc_auth.*
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.io.File
import java.io.FileOutputStream


@Immersive(fitSystemWindows = false)
class KycAuthActivity :
    BaseMvpActivity<KycAuthContract.Presenter>(), KycAuthContract.View {

    //是否kyc认真 true:不可编辑  false:可编辑
    private var isKycAuth = true


    //拍照的照片的存储位置
    private val mTempPhotoPath :String? = null
    //照片所在的Uri地址
    private var imageUri:Uri? = null
    //图片对象
    private var imageFile: File? = null

    private var isSide = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //修改底部功能键背景色 只支持api为21及以上
        if (Build.VERSION.SDK_INT  >= Build.VERSION_CODES.LOLLIPOP) {
            window.navigationBarColor = ResourcesUtil.getColor(R.color.colorPrimary) //设定底部导航栏  同全局颜色
        }
    }
    override fun setupActivityComponent(appComponent: AppComponent) {
        DaggerKycAuthActivityComponent.builder()
            .kycAuthActivityModule(KycAuthActivityModule(this))
            .appComponent(appComponent)
            .activityModule(ActivityModule(this))
            .build()
            .inject(this)
    }

    override fun initView(savedInstanceState: Bundle?): Int = R.layout.activity_kyc_auth

    override fun initData(savedInstanceState: Bundle?) {
        initBtnClick()
        presenter.loadKycDetail(150)
    }

    /**
     * 提交审核后响应
     */
    override fun onSubmitKycAuthResultResp(response: CommonResponse<JSONObject>) {
        if (response.code == Constants.RESP_OK) {
            Toast.makeText(this, "提交成功", Toast.LENGTH_SHORT).show()
            btnSubmitKycAuth.visibility = View.GONE
            presenter.loadKycDetail(150)
        }else {
            btnSubmitKycAuth.visibility = View.VISIBLE
            Toast.makeText(this, response.msg, Toast.LENGTH_SHORT).show()
        }
    }

    /**
     * 用户获取Kyc认证信息响应
     */
    override fun onLoadKycDetailResultResp(response: CommonResponse<JSONObject>) {
        isKycAuth = true
        if (response.code == Constants.RESP_OK && !response.data.isNullOrEmpty()) {
            var data = response.data
            try {
                tvKycAuthStatus.text = KycAuthStatusConstant.getRemarkByValue(data.getInteger("status"))

                tvKycAuthRealName.text = DataUtil.enString(data.getString("real_name"))
                tvKycAuthIdCardNo.text = DataUtil.enString(data.getString("id_card_no"))
                tvKycAuthQQ.text = DataUtil.enString(data.getString("qq"))
                tvKycAuthWechat.text = DataUtil.enString(data.getString("wechat"))
                tvKycAuthEmail.text = DataUtil.enString(data.getString("email"))

                etKycAuthRealName.setText(data.getString("real_name"))
                etKycAuthIdCardNo.setText(data.getString("id_card_no"))
                etKycAuthQQ.setText(data.getString("qq"))
                etKycAuthWechat.setText(data.getString("wechat"))
                etKycAuthEmail.setText(data.getString("email"))
                var frontImageUrl = data.getString("front_id_card_url")
                var backImageUrl = data.getString("back_id_card_url")
                if (!frontImageUrl.isNullOrEmpty()) {
                    Glide.with(this).load(frontImageUrl).into(ivKycAuthFrontPhoto)
                }
                if (!backImageUrl.isNullOrEmpty()) {
                    Glide.with(this).load(backImageUrl).into(ivKycAuthBackPhoto)
                }
                //可编辑
                if (KycAuthStatusConstant.isUserEdit(data.getInteger("status"))) {
                    isKycAuth = false
                    llKycAuthPhotos.visibility = View.VISIBLE
                }else {
                    llKycAuthPhotos.visibility = View.GONE
                }
            }catch (e :Exception) {
                tvKycAuthStatus.text = "未认证"

                tvKycAuthRealName.text = ""
                tvKycAuthIdCardNo.text = ""
                tvKycAuthQQ.text = ""
                tvKycAuthWechat.text = ""
                tvKycAuthEmail.text = ""

                etKycAuthRealName.setText("")
                etKycAuthIdCardNo.setText("")
                etKycAuthQQ.setText("")
                etKycAuthWechat.setText("")
                etKycAuthEmail.setText("")

                logger.e("用户获取Kyc认证信息失败", e)
                btnSubmitKycAuth.visibility = View.GONE
            }
            if(tvKycAuthStatus.text.equals("审核通过")){
                PreferencesUtil.saveValue("isAlreadyKycAuth",true)
            }else{
                PreferencesUtil.saveValue("isAlreadyKycAuth",false)
            }

        }
        initItem()
    }

    /**
     * 用户图片提交验证
     */
    override fun onKycUploadResultResp(response: CommonResponse<String>) {

        if (response.code == Constants.RESP_OK) {
            if (!isSide) {
                Glide.with(this).load(response.data).into(ivKycAuthFrontPhoto)
            } else {
                Glide.with(this).load(response.data).into(ivKycAuthBackPhoto)
            }
        }else {
            logger.e(response.msg)
            Toast.makeText(this, "上传图片失败", Toast.LENGTH_SHORT).show()
        }
    }

    override fun onError(type: Int, extra: Any?, code: Int, message: String): Boolean {
        logger.e("error >>> $message")
        return super.onError(type, extra, code, message)
    }

    private fun initBtnClick() {
        btnBack.setOnClickListener({
            this.finish()
        })

        //提交审核按钮
        btnSubmitKycAuth.setOnClickListener({
            submitKycAuth()

        })

        //点击选择正面照
        ivKycAuthFrontPhoto.setOnClickListener({
            if (isKycAuth) {
                return@setOnClickListener
            }
            isSide = false
            openSysCamera()
        })
        //点击选择反面照
        ivKycAuthBackPhoto.setOnClickListener({
            if (isKycAuth) {
                return@setOnClickListener
            }
            isSide = true
            openSysCamera()
        })
    }

    /**
     * 提价kyc审核
     */
    private fun submitKycAuth() {
        var realName = etKycAuthRealName.text.trim().toString()
        var idCardNo = etKycAuthIdCardNo.text.trim().toString()
        var qq: String? = etKycAuthQQ.text.trim().toString()
        var wechat: String? = etKycAuthWechat.text.trim().toString()
        var email: String? = etKycAuthEmail.text.trim().toString()

        if (realName.isNullOrEmpty()) {
            Toast.makeText(this, "请输入真实姓名", Toast.LENGTH_SHORT).show()
            return
        }
        if (idCardNo.isNullOrEmpty()) {
            Toast.makeText(this, "请输入身份证号", Toast.LENGTH_SHORT).show()
            return
        }
        if (qq.isNullOrEmpty() && wechat.isNullOrEmpty() && email.isNullOrEmpty()) {
            Toast.makeText(this, "qq,微信和邮箱不能都为空", Toast.LENGTH_SHORT).show()
            return
        }
        if (!validateIdCard(idCardNo)) {
            Toast.makeText(this, "请输入正确的身份证号", Toast.LENGTH_SHORT).show()
            return
        }
        if (!email.isNullOrEmpty() && !isEmail(email)) {
            Toast.makeText(this, "请输入正确的邮箱地址", Toast.LENGTH_SHORT).show()
            return
        }
        if (qq.isNullOrEmpty()) {
            qq = null
        }
        if (email.isNullOrEmpty()) {
            email = null
        }

        if (wechat.isNullOrEmpty()) {
            wechat = null
        }
        presenter.submitKycAuth(KycAuthResVo(realName,idCardNo,email,qq,wechat))
    }

    /**
     * 初始化组件
     */
    private fun initItem() {
        if (isKycAuth) {
            tvKycAuthRealName.visibility = View.VISIBLE
            tvKycAuthIdCardNo.visibility = View.VISIBLE
            tvKycAuthQQ.visibility = View.VISIBLE
            tvKycAuthWechat.visibility = View.VISIBLE
            tvKycAuthEmail.visibility = View.VISIBLE

            etKycAuthRealName.visibility = View.GONE
            etKycAuthIdCardNo.visibility = View.GONE
            etKycAuthQQ.visibility = View.GONE
            etKycAuthWechat.visibility = View.GONE
            etKycAuthEmail.visibility = View.GONE

            btnSubmitKycAuth.visibility = View.GONE
        }else {
            etKycAuthRealName.visibility = View.VISIBLE
            etKycAuthIdCardNo.visibility = View.VISIBLE
            etKycAuthQQ.visibility = View.VISIBLE
            etKycAuthWechat.visibility = View.VISIBLE
            etKycAuthEmail.visibility = View.VISIBLE
            btnSubmitKycAuth.visibility = View.VISIBLE

            tvKycAuthRealName.visibility = View.GONE
            tvKycAuthIdCardNo.visibility = View.GONE
            tvKycAuthQQ.visibility = View.GONE
            tvKycAuthWechat.visibility = View.GONE
            tvKycAuthEmail.visibility = View.GONE
        }
    }

    /**
     * 打开系统相机
     */
    private fun openSysCamera() {
        var cameraIntent =  Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        imageFile = File(externalCacheDir, "output_image.jpg")
        if (Build.VERSION.SDK_INT >= 24) {
             imageUri = FileProvider.getUriForFile(this, Constants.ACTION_FILE_PROVIDER,
                 imageFile!!
             )
        }else {
            imageUri = Uri.fromFile(imageFile)
        }
        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri)
        startActivityForResult(cameraIntent, CommonConstant.CAMERA_REQUEST_CODE)


    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (resultCode == -1) {
            // 创建 RequestBody，用于封装构建RequestBody
            //压缩图片 reduceImage
            var requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), reduceImage(imageFile))
            // MultipartBody.Part  和后端约定好Key，这里的partName是用file
            var body = MultipartBody.Part.createFormData("file", imageFile!!.name, requestFile)
            if (isSide) {
                presenter.kycUpload(body,"back", 150)
            }else {
                presenter.kycUpload(body,"front", 150)
            }

        }

        super.onActivityResult(requestCode, resultCode, data)
    }

    /**
     * 压缩图片
     */
    fun  reduceImage(sourFile: File?): File {
        var bitmap: Bitmap
        bitmap = BitmapFactory.decodeFile(sourFile!!.path)
        var file = File(externalCacheDir, "output_image_temp.jpg")
        try {
            var quality = 100
            while(true) {
                var fileOutputStream = FileOutputStream(file)
                bitmap.compress(Bitmap.CompressFormat.JPEG, quality, fileOutputStream)
                quality -= 10
                var length = file.length()
                if (length < (1024 * 1024)) {
                    break
                }
            }
            return file
        }catch (e:Exception){
            e.printStackTrace()
        }
        return file
    }

    /**
     * 验证身份证号
     */
    private fun validateIdCard(cardNo: String?): Boolean {
        cardNo ?: return false
        if (cardNo.length != 18 || !cardNo.substring(0, 17).matches(Regex("\\d{17}"))) {
            return false
        }
        // 身份证号前17位分别和下面的array中对应的值相乘之后求和
        // 然后模11之后的结果作为数组下标,去validCodes中取正确的尾号和参数中的尾号做校验接即可
        val intArr = arrayOf(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2)
        var sum = 0
        for (idx in intArr.indices) {
            sum += Character.digit(cardNo[idx], 10) * intArr[idx]
        }
        val mod = sum % 11
        val validCodes = arrayOf("1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2")
        return validCodes[mod] == cardNo.substring(cardNo.length - 1)
    }

    /**
     * 验证邮箱
     */
    fun isEmail(strEmail: String): Boolean {
        val regex =
            "^[a-zA-Z0-9][\\w\\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\\w\\.-]*[a-zA-Z0-9]\\.[a-zA-Z][a-zA-Z\\.]*[a-zA-Z]$".toRegex()
         return strEmail.matches(regex)

    }
    companion object {
        fun startActivity(context: Context) {
            Intent(context, KycAuthActivity::class.java).run {
                context.startActivity(this)
            }
        }

    }

}
